package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.finance;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.BalanceDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.CFinaceEnterDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.approve.ApproveBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.BalanceEnquiryExcelEn;

import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.RechargeRecordExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CCompanysMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CFinaceEnterMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.COrderDetailMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightSheetsMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.Constructor.FinaceEnterVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.CreditVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetBalanceEnquiryVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;

@Component
public class BalanceEnquiryBu {
    @Autowired
    private ICOrderDetailService iCOrderDetailService;
    @Autowired
    private CWeightSheetsMapper cWeightSheetsMapper;
    @Autowired
    private ICFinaceEnterService iCFinaceEnterService;
    @Autowired
    private ICCompanysService iCCompanysService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private BalanceDic balanceDic;
    @Autowired
    private CFinaceEnterDic cFinaceEnterDic;
    @Autowired
    private CFinaceEnterMapper cFinaceEnterMapper;

    @Autowired
    private ICWeightSheetsService iCWeightSheetsService;
    @Autowired
    private CCompanysMapper cCompanysMapper;
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ApproveBu approveBu;
    @Autowired
    private ITApproveInfoService approveInfoService;
    @Autowired
    private COrderDetailMapper cOrderDetailMapper;


    /**
     * 根据客户名称查询余额
     *
     * @param co 客户名称
     *           startTime 开始时间
     *           endTime 结束时间
     *           方法作用：根据客户名称查询余额，根据startTime和endTime查询时间段内的余额
     * @return com.xiaoxu.intranetweb.util.SzResult
     */
    public SzResult getBalanceEnquiry(String co, String chiCo, String startTime, String endTime, String token, String plantId) throws Exception {
        //将token转为plantId
        // String plantId = plantId;
        //String plantId = plantId;
        QueryWrapper<COrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(co != null && !co.equals(""), "ORDETAIL_CO", co);
//        ORDETAIL_CHICO
        queryWrapper.eq(chiCo != null && !chiCo.equals(""), "ORDETAIL_CHICO", chiCo);
        queryWrapper.eq("ORDETAIL_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.orderByAsc("ORDETAIL_CO");

        List<COrderDetail> list = iCOrderDetailService.list(queryWrapper);
        List<GetBalanceEnquiryVo> getBalanceEnquiryVoList = new ArrayList<>();
        for (COrderDetail cOrderDetail : list) {
            GetBalanceEnquiryVo getBalanceEnquiryVo = new GetBalanceEnquiryVo();
            getBalanceEnquiryVo.setId(cOrderDetail.getId());
            getBalanceEnquiryVo.setOrdetailId(String.valueOf(cOrderDetail.getOrdetailId()));
            getBalanceEnquiryVo.setOrdetailCo(cOrderDetail.getOrdetailCo());
            getBalanceEnquiryVo.setOrdetailChico(cOrderDetail.getOrdetailChico());
            getBalanceEnquiryVo.setOrdetailSubId(cOrderDetail.getOrdetailSubId());
            if(cOrderDetail.getOrdetailSubId() !=null) {
                CCompanys cCompanys = cCompanysMapper.getCompanyById(cOrderDetail.getOrdetailSubId(), plantId);
                if(cCompanys !=null) {
                    getBalanceEnquiryVo.setOrdetailSubName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());
                }else {
                    getBalanceEnquiryVo.setOrdetailSubName("");
                }
            }
            getBalanceEnquiryVo.setOrdetailPdt(cOrderDetail.getOrdetailPdt());
            getBalanceEnquiryVo.setOrdetailItemNum(cOrderDetail.getOrdetailItemNum());
//            原本是使用cOrderDetail.getOrdetailRemainNum()的，但是因为有负价格的余额，所以就只能使用sob1作为余额了
//             getBalanceEnquiryVo.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum());
            getBalanceEnquiryVo.setOrdetailRemainNum(cOrderDetail.getOrdetailSob1RemainNum());
            getBalanceEnquiryVo.setOrdetailPreLic(cOrderDetail.getOrdetailPreLic());
            getBalanceEnquiryVo.setOrdetailLastinNum(cOrderDetail.getOrdetailLastinNum());
            getBalanceEnquiryVo.setOrdetailLastoutNum(cOrderDetail.getOrdetailLastoutNum());
            getBalanceEnquiryVo.setOrdetailSob1Num(cOrderDetail.getOrdetailSob1Num());
            getBalanceEnquiryVo.setOrdetailSob1RemainNum(cOrderDetail.getOrdetailSob1RemainNum());
            getBalanceEnquiryVo.setOrdetailSob1LastinNum(cOrderDetail.getOrdetailSob1LastinNum());
            getBalanceEnquiryVo.setOrdetailSob2Num(cOrderDetail.getOrdetailSob2Num());
            getBalanceEnquiryVo.setOrdetailSob2RemainNum(cOrderDetail.getOrdetailSob2RemainNum());
            getBalanceEnquiryVo.setOrdetailSob2LastinNum(cOrderDetail.getOrdetailSob2LastinNum());
            getBalanceEnquiryVo.setOrdetailSob3Num(cOrderDetail.getOrdetailSob3Num());
            getBalanceEnquiryVo.setOrdetailSob3RemainNum(cOrderDetail.getOrdetailSob3RemainNum());
            getBalanceEnquiryVo.setOrdetailSob3LastinNum(cOrderDetail.getOrdetailSob3LastinNum());
            getBalanceEnquiryVo.setOrdetailSob4Num(cOrderDetail.getOrdetailSob4Num());
            getBalanceEnquiryVo.setOrdetailSob4RemainNum(cOrderDetail.getOrdetailSob4RemainNum());
            getBalanceEnquiryVo.setOrdetailSob4LastinNum(cOrderDetail.getOrdetailSob4LastinNum());
            getBalanceEnquiryVo.setOrdetailSob5Num(cOrderDetail.getOrdetailSob5Num());
            getBalanceEnquiryVo.setOrdetailSob5RemainNum(cOrderDetail.getOrdetailSob5RemainNum());
            getBalanceEnquiryVo.setOrdetailSob5LastinNum(cOrderDetail.getOrdetailSob5LastinNum());
            getBalanceEnquiryVo.setOrdetailLastCredence(cOrderDetail.getOrdetailLastCredence());
            getBalanceEnquiryVo.setOrdetailExecutePrice(cOrderDetail.getOrdetailExecutePrice());
            getBalanceEnquiryVo.setOrdetailModifyTime(cOrderDetail.getOrdetailModifyTime());
            getBalanceEnquiryVo.setOrdetailTempout(cOrderDetail.getOrdetailTempout());
            getBalanceEnquiryVo.setOrdetailDeleted(cOrderDetail.getOrdetailDeleted());
            getBalanceEnquiryVo.setOrdetailNew(cOrderDetail.getOrdetailNew());
            getBalanceEnquiryVo.setDownedID1(cOrderDetail.getDownedID1());
            getBalanceEnquiryVo.setDownedID2(cOrderDetail.getDownedID2());
            getBalanceEnquiryVo.setDownedID3(cOrderDetail.getDownedID3());
            getBalanceEnquiryVo.setDownedID4(cOrderDetail.getDownedID4());
            getBalanceEnquiryVo.setDownedID5(cOrderDetail.getDownedID5());
            getBalanceEnquiryVo.setDownedID6(cOrderDetail.getDownedID6());
            getBalanceEnquiryVo.setDownedID7(cOrderDetail.getDownedID7());
            getBalanceEnquiryVo.setDownedID8(cOrderDetail.getDownedID8());
            getBalanceEnquiryVo.setDownedID9(cOrderDetail.getDownedID9());
            getBalanceEnquiryVo.setDownedID10(cOrderDetail.getDownedID10());
            getBalanceEnquiryVo.setDownedID11(cOrderDetail.getDownedID11());
            getBalanceEnquiryVo.setDownedID12(cOrderDetail.getDownedID12());
            getBalanceEnquiryVo.setDownedID13(cOrderDetail.getDownedID13());
            getBalanceEnquiryVo.setDownedID14(cOrderDetail.getDownedID14());
            getBalanceEnquiryVo.setDownedID15(cOrderDetail.getDownedID15());
            getBalanceEnquiryVo.setDownedID16(cOrderDetail.getDownedID16());
            getBalanceEnquiryVo.setDownedID17(cOrderDetail.getDownedID17());
            getBalanceEnquiryVo.setDownedID18(cOrderDetail.getDownedID18());
            getBalanceEnquiryVo.setDownedID19(cOrderDetail.getDownedID19());
            getBalanceEnquiryVo.setDownedID20(cOrderDetail.getDownedID20());
            getBalanceEnquiryVo.setDataFrom(cOrderDetail.getDataFrom());
         /*   // 创建GetBalanceEnquiryVo对象
            GetBalanceEnquiryVo getBalanceEnquiryVo = new GetBalanceEnquiryVo();

// 将属性值拷贝到GetBalanceEnquiryVo对象中
            try {
                BeanUtils.copyProperties(getBalanceEnquiryVo, cOrderDetail);
            } catch (Exception e) {
                e.printStackTrace();
            }

// 设置OrdetailSubName属性

            CCompanys cCompanys = cCompanysMapper.getCompanyById(cOrderDetail.getOrdetailSubId(), plantId);
            getBalanceEnquiryVo.setOrdetailSubName(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico());*/
            //开始时间到结束时间内消费金额
//            GetBalanceEnquiryVo getBalanceEnquiryVo1 = cWeightSheetsMapper.getBalanceEnquiry(startTime, endTime, cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), plantId);
//            //结束时间到现在时间区间内消费金额
//            LocalDateTime now = LocalDateTime.now();
//            GetBalanceEnquiryVo getBalanceEnquiryVo2 = cWeightSheetsMapper.getBalanceEnquiry(endTime, String.valueOf(now), cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), plantId);
//            String ordetailSubId = cOrderDetail.getOrdetailSubId();
//            QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
//            companysQueryWrapper.eq("ID", ordetailSubId);
//            CCompanys cCompanys1 = iCCompanysService.getOne(companysQueryWrapper);
//            String supplyCo = cCompanys1.getCpyCo();
//            String supplyChiCo = cCompanys1.getCpyChico();
//            //消费
//            GetBalanceEnquiryVo balanceEnd = cWeightSheetsMapper.getBalanceEnd(endTime, cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), supplyCo, supplyChiCo, plantId);
//
//            //充值
//            GetBalanceEnquiryVo balanceEnd2 = cWeightSheetsMapper.getBalanceEnd2(endTime, cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), String.valueOf(ordetailSubId), plantId);
//            //时间点止余额（元）
//            if (balanceEnd == null) {//时间内没有消费
//                if (balanceEnd2 != null) {//但是有充值
//                    getBalanceEnquiryVo.setBalanceEnd(balanceEnd2.getBalanceEnd());
//                }
//            }
//            if (balanceEnd2 == null) {//没有充值
//                if (balanceEnd != null) {//但是有消费
//                    getBalanceEnquiryVo.setBalanceEnd(-balanceEnd.getBalanceEnd());
//                }
//            }
//            if (balanceEnd != null && balanceEnd2 != null) {//有充值也有消费
//                getBalanceEnquiryVo.setBalanceEnd(balanceEnd2.getBalanceEnd() - balanceEnd.getBalanceEnd());
//            }
//            //时间点期间扣款（元）
//            if (getBalanceEnquiryVo1 != null) {
//                getBalanceEnquiryVo.setBalanceConsume(getBalanceEnquiryVo1.getBalanceConsume());
//            } else {
//                getBalanceEnquiryVo.setBalanceConsume(0.0);
//            }
            getBalanceEnquiryVoList.add(getBalanceEnquiryVo);
        }
        return SzResult.success(getBalanceEnquiryVoList);
    }


    //获取时间点余额方法
    public Double balanceEnd(String token, String co, String chi, String endTime, String plantId) throws Exception {
        BigDecimal balanceEnd;
        //获取时间点止余额的充值金额
        QueryWrapper<CFinaceEnter> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("FINANCE_ENTER_NUM"); // 只选择需要的字段
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq(co != null && !co.equals(""), "FINANCE_ENTER_CO", co);
        queryWrapper.eq(chi != null && !chi.equals(""), "FINANCE_ENTER_CHI_CO", chi);
        queryWrapper.le(endTime != null && !endTime.equals(""), "FINANCE_ENTER_TIME", endTime);//小于等于
        //把所有查出
        List<CFinaceEnter> list = iCFinaceEnterService.list(queryWrapper);
        BigDecimal FinaceEnterBalanceEnd = BigDecimal.ZERO;
        for (CFinaceEnter cFinaceEnter : list) {
            BigDecimal financeEnterNum = cFinaceEnter.getFinanceEnterNum();
            FinaceEnterBalanceEnd = FinaceEnterBalanceEnd.add(financeEnterNum);
        }

        //获取时间点止余额的消费金额
        QueryWrapper<CWeightSheets> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("WEISHT_MONEY"); // 只选择需要的字段
        queryWrapper1.eq("DATA_FROM", plantId);
        queryWrapper1.eq(co != null && !co.equals(""), "WEISHT_CO_SUPPLY", co);
        queryWrapper1.eq(chi != null && !chi.equals(""), "WEISHT_CO_SUPPLY_CHI", chi);
        queryWrapper1.le(endTime != null && !endTime.equals(""), "WEISHT_FULL_TM", endTime);//小于等于
        List<CWeightSheets> list1 = iCWeightSheetsService.list(queryWrapper1);
        BigDecimal CWeightSheetsBalanceEnd = BigDecimal.ZERO;
        if (list1 != null) {
            for (CWeightSheets cWeightSheets : list1) {
                BigDecimal weishtNum = cWeightSheets.getWeishtMoney();
                CWeightSheetsBalanceEnd = CWeightSheetsBalanceEnd.add(weishtNum);
            }
        }
        QueryWrapper<CWeightSheets> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("WEISHT_MONEY"); // 只选择需要的字段
        queryWrapper2.eq("DATA_FROM", plantId);
        queryWrapper2.eq(co != null && !co.equals(""), "WEISHT_CO", co);
        queryWrapper2.eq(chi != null && !chi.equals(""), "WEISHT_CHI_CO", chi);
        queryWrapper2.le(endTime != null && !endTime.equals(""), "WEISHT_FULL_TM", endTime);//小于等于
        List<CWeightSheets> list2 = iCWeightSheetsService.list(queryWrapper2);
        BigDecimal CWeightSheetsBalanceEnd1 = BigDecimal.ZERO;
        if (list2 != null) {
            for (CWeightSheets cWeightSheets : list2) {
                BigDecimal weishtNum = cWeightSheets.getWeishtMoney();
                CWeightSheetsBalanceEnd1 = CWeightSheetsBalanceEnd1.add(weishtNum);
            }
        }
        balanceEnd = FinaceEnterBalanceEnd.add(CWeightSheetsBalanceEnd).add(CWeightSheetsBalanceEnd1);
        //將BigDecimal转换为Double
        return balanceEnd.doubleValue();
    }
    /**
     * 查询充值记录
     *
     * @param page      页码
     * @param pageSize  每页条数
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param co        公司
     * @return 充值记录
     */
    public SzResult getRechargeRecord(String page, String pageSize, String startTime, String endTime, String co, String chiCo,String financeSubjectId, String token, String plantId) throws Exception {
        Page<CFinaceEnter> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
        QueryWrapper<CFinaceEnter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(co != null && !co.equals(""), "FINANCE_ENTER_CO", co);
        queryWrapper.eq(chiCo != null && !chiCo.equals(""), "FINANCE_ENTER_CHI_CO", chiCo);
        queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "FINANCE_ENTER_TIME", startTime, endTime);
        queryWrapper.eq(financeSubjectId !=null && !financeSubjectId.equals(""),"FINANCE_SUBJECT_ID", financeSubjectId);
        queryWrapper.eq("FINANCE_ENTER_DELETED", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.orderByDesc("FINANCE_ENTER_TIME");
        IPage<CFinaceEnter> iPage = iCFinaceEnterService.page(page1, queryWrapper);
        List<CFinaceEnter> cFinaceEnterList = iPage.getRecords();
        List<FinaceEnterVo> cFinaceEnterVoList = new ArrayList<>();
        for (CFinaceEnter cFinaceEnter : cFinaceEnterList) {
            String financeEnterCo = cFinaceEnter.getFinanceEnterCo();
            String financeEnterChiCo = cFinaceEnter.getFinanceEnterChiCo();
            String subjectId = String.valueOf(cFinaceEnter.getFinanceSubjectId());
            QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ID", subjectId);
            CCompanys cCompanys = iCCompanysService.getOne(queryWrapper1);
            FinaceEnterVo finaceEnterVo = new FinaceEnterVo();
            finaceEnterVo.setId(cFinaceEnter.getId());
            finaceEnterVo.setFinanceEnterId(String.valueOf(cFinaceEnter.getFinanceEnterId()));
            finaceEnterVo.setFinanceEnterCo(financeEnterCo);
            finaceEnterVo.setFinanceEnterChiCo(financeEnterChiCo);
            finaceEnterVo.setFinanceEnterNum(String.valueOf(cFinaceEnter.getFinanceEnterNum()));
            finaceEnterVo.setExchangeNo(cFinaceEnter.getExchangeNo());
            finaceEnterVo.setFinanceEnterTime(cFinaceEnter.getFinanceEnterTime());
            finaceEnterVo.setFinanceEnterRemark(cFinaceEnter.getFinanceEnterRemark());
            finaceEnterVo.setFinanceApprver(cFinaceEnter.getFinanceApprver());
            finaceEnterVo.setFinanceApprvTm(cFinaceEnter.getFinanceApprvTm());
            finaceEnterVo.setFinanceApprver2(cFinaceEnter.getFinanceApprver2());
            finaceEnterVo.setFinanceApprvTm2(cFinaceEnter.getFinanceApprvTm2());
            finaceEnterVo.setSfnFinanceApprved(String.valueOf(cFinaceEnter.getSfnFinanceApprved()));
            finaceEnterVo.setSfnFinanceApprved2(String.valueOf(cFinaceEnter.getSfnFinanceApprved2()));
            finaceEnterVo.setFinanceSubjectId(subjectId);
            if (cCompanys != null) {
                finaceEnterVo.setFinanceSubjectName(cCompanys.getCpyCo());
                finaceEnterVo.setFinanceSubjectChiName(cCompanys.getCpyChico());
            }

            finaceEnterVo.setFinanceEnterOperator(cFinaceEnter.getFinanceEnterOperator());
            finaceEnterVo.setFinanceEntered(String.valueOf(cFinaceEnter.getFinanceEntered()));
            cFinaceEnterVoList.add(finaceEnterVo);
        }
        Long total = iPage.getTotal();
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("list", cFinaceEnterVoList);
        return SzResult.success(map);
    }

    /**
     * 新增充值记录
     *
     * @param financeEnterCoId   充值公司ID
     * @param targetCoId         目标公司ID
     * @param financeEnterNum    充值金额（元）
     * @param financeEnterRemark 充值备注
     */
    @Transactional
    public SzResult addRechargeRecord(String financeEnterCoId, String targetCoId, String financeEnterNum, String financeEnterRemark, String exchangeNo, String token, String plantId) throws Exception {
//        这里targetCoId传的是短id转成uuid
        QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
        companysQueryWrapper.eq("ID", financeEnterCoId);
        companysQueryWrapper.eq("DATA_FROM",plantId);
        CCompanys cCompanys1 = iCCompanysService.getOne(companysQueryWrapper);
        // String plantId = plantId;
       String uuid =  java.util.UUID.randomUUID().toString().replace("-", "");
        QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", targetCoId);
        queryWrapper.eq("CPY_DELETED", 0);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper);
        if (cCompanys == null) {
            return SzResult.Error("公司不存在");
        }
        CFinaceEnter cFinaceEnter = new CFinaceEnter();

        cFinaceEnter.setFinanceEnterCo(cCompanys1.getCpyCo());
        cFinaceEnter.setFinanceEnterChiCo(cCompanys1.getCpyChico());
        if (financeEnterNum != null && !financeEnterNum.equals("")) {
            cFinaceEnter.setFinanceEnterNum(new BigDecimal(financeEnterNum));
        } else {
            return SzResult.error("充值金额不能为空");
        }
        cFinaceEnter.setFinanceEnterTime(LocalDateTime.now());
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        cFinaceEnter.setFinanceEnterOperator(user.getTrueName());

        if (financeEnterRemark != null && !financeEnterRemark.equals("")) {
            cFinaceEnter.setFinanceEnterRemark(financeEnterRemark);//充值备注
        }
        cFinaceEnter.setFinanceEnterDeleted(0);
//充值编号为当天的时间加上充值的第几笔
        cFinaceEnter.setId(uuid);
//            setFinanceEnterId是BigDecimal类型的，所以要转换
//            cFinaceEnter.setFinanceEnterId(uuid);
        String date = DateUtil.format(new Date(), "yyyyMMdd");

        String maxFinanceEnterId = cFinaceEnterMapper.getMaxFinanceEnterId(date, plantId);
        if (maxFinanceEnterId == null) {
//            setFinanceEnterId是BigDecimal类型的，所以要转换
            cFinaceEnter.setFinanceEnterId(BigDecimal.valueOf(Long.parseLong(DateUtil.format(new Date(), "yyyyMMdd") + "001")));
        } else {
            //            substring是截取字符串，截取最后三位，也就是001
            String substring = maxFinanceEnterId.substring(maxFinanceEnterId.length() - 3);
//            substring1是截取前面的20230601
            String substring1 = maxFinanceEnterId.substring(0, maxFinanceEnterId.length() - 3);
//            substring2是截取的001转换成int类型的1
            int substring2 = Integer.parseInt(substring) + 1;
//            substring3是把1转换成字符串类型的001
            String substring3 = String.format("%03d", substring2);
//            substring4是把20230601和001拼接成20230601001
            String substring4 = substring1 + substring3;
//            substring5是把20230601001转换成BigDecimal类型的20230601001
//                BigDecimal substring5 = new BigDecimal();
            cFinaceEnter.setFinanceEnterId(BigDecimal.valueOf(Long.parseLong(substring4)));
        }
        cFinaceEnter.setFinanceEnterDeleted(0);
        cFinaceEnter.setFinanceEntered(0);//是否入账，未入账
        cFinaceEnter.setExchangeNo(exchangeNo);
        cFinaceEnter.setFinanceSubjectId(targetCoId);
        cFinaceEnter.setDataFrom(plantId);
        cFinaceEnter.setFinanceEnterTime(LocalDateTime.now());
        cFinaceEnter.setFinancePayTime(LocalDateTime.now());
        iCFinaceEnterService.save(cFinaceEnter);
        QueryWrapper<TApprove> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("IF_ON", 1);
        queryWrapper2.eq("DEL_FLAG", 0);
        queryWrapper2.eq("DATA_FROM", plantId);
        queryWrapper2.eq("APPROVE_NAME", "recharge");
        TApprove tApprove = approveService.getOne(queryWrapper2);
        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveBelongId(String.valueOf(cFinaceEnter.getFinanceEnterId()));
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的充值审批：" + "往【" + cCompanys1.getCpyCo() + "." + cCompanys1.getCpyChico() + "】公司充值" + financeEnterNum + "元");
            tApproveInfo.setDataFrom(plantId);
            //String financeEnterNum, String financeEnterCoId, String targetCoId, String token放到json里面，然后存到  tApproveInfo.setExecutionData
            Map<String, Object> map = new HashMap<>();
            map.put("financeEnterNum", financeEnterNum);
            map.put("financeEnterCoId", financeEnterCoId);
            map.put("targetCoId", targetCoId);
            map.put("plantId", plantId);
//            ID
            map.put("financeEnterId", cFinaceEnter.getId());
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            approveInfoService.save(tApproveInfo);
            return SzResult.success("新增成功,等待审批");
        }//没开启审批,打款,并且入账
        this.addOrderDetail(financeEnterNum, financeEnterCoId, targetCoId, plantId);//打款
        cFinaceEnter.setFinanceEntered(1);//是否入账
        iCFinaceEnterService.updateById(cFinaceEnter);
        sysLogBu.logRecord("新增款项进账", user.getTrueName(), "新增了充值公司为【" + cCompanys1.getCpyCo()+cCompanys1.getCpyChico() + "】" + "金额【" + financeEnterNum + "】的款项进账", plantId);
        return SzResult.Success();
    }

    public void addOrderDetail(String financeEnterNum, String financeEnterCoId, String targetCoId, String plantId) throws Exception {
String uuid =  java.util.UUID.randomUUID().toString().replace("-", "");
        QueryWrapper<CCompanys> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", financeEnterCoId);
        queryWrapper.eq("CPY_DELETED", 0);
//        queryWrapper.eq("CPY_PASS", 0);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper);
        COrderDetail cOrderDetail;
        QueryWrapper<COrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ORDETAIL_CO", cCompanys.getCpyCo());
        queryWrapper1.eq("ORDETAIL_CHICO", cCompanys.getCpyChico());
        queryWrapper1.eq("ORDETAIL_SUB_ID", targetCoId);

        cOrderDetail = iCOrderDetailService.getOne(queryWrapper1);
        //  String plantId = plantId;
        if (cOrderDetail == null) {//没有这个账户

            //新增账户
            COrderDetail cOrderDetail1 = new COrderDetail();
            cOrderDetail1.setId(uuid);
//                cOrderDetail1.setOrdetailId(uuid);
            QueryWrapper<COrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
            orderDetailQueryWrapper.orderByDesc("ORDETAIL_ID");
            orderDetailQueryWrapper.last("limit 1");
            orderDetailQueryWrapper.eq("DATA_FROM", plantId);
            COrderDetail cOrderDetail2 = iCOrderDetailService.getOne(orderDetailQueryWrapper);
            if (cOrderDetail2 != null) {
                BigDecimal ordetailId = cOrderDetail2.getOrdetailId();
                String ordetailId1 = String.valueOf((ordetailId.intValue() + 1));
                cOrderDetail1.setOrdetailId(new BigDecimal(ordetailId1));
            } else {
                cOrderDetail1.setOrdetailId(new BigDecimal(1));
            }
                cOrderDetail1.setOrdetailItemNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
                cOrderDetail1.setOrdetailRemainNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
                cOrderDetail1.setOrdetailLastinNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
                if (Double.parseDouble(financeEnterNum) < 0) {
                    cOrderDetail1.setOrdetailLastoutNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
                } else {
                    cOrderDetail1.setOrdetailLastoutNum(BigDecimal.valueOf(0));
                }
            cOrderDetail1.setOrdetailCo(cCompanys.getCpyCo());
            cOrderDetail1.setOrdetailChico(cCompanys.getCpyChico());
            cOrderDetail1.setOrdetailSubId(targetCoId);
            cOrderDetail1.setOrdetailModifyTime(LocalDateTime.now());
            cOrderDetail1.setDataFrom(plantId);
            cOrderDetail1.setOrdetailDeleted(0);
            cOrderDetail1.setOrdetailSob1Num(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
            cOrderDetail1.setOrdetailLastinNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
            cOrderDetail1.setOrdetailSob1RemainNum(BigDecimal.valueOf(Double.parseDouble(financeEnterNum)));
            iCOrderDetailService.save(cOrderDetail1);
        } else {//有这个账户
            String ordetailId = cOrderDetail.getId();

            cOrderDetailMapper.insertOrderDetail(financeEnterNum, plantId, ordetailId);
          /*   cOrderDetail.setOrdetailItemNum(cOrderDetail.getOrdetailItemNum().add(BigDecimal.valueOf(Long.parseLong(financeEnterNum))));
            cOrderDetail.setOrdetailRemainNum(cOrderDetail.getOrdetailRemainNum().add(BigDecimal.valueOf(Long.parseLong(financeEnterNum))));
            cOrderDetail.setOrdetailLastinNum(BigDecimal.valueOf(Long.parseLong(financeEnterNum)));
            if (Integer.parseInt(financeEnterNum) < 0) {
                cOrderDetail.setOrdetailLastoutNum(BigDecimal.valueOf(Long.parseLong(financeEnterNum)));
            } else {
                cOrderDetail.setOrdetailLastoutNum(BigDecimal.valueOf(0));
            }
            cOrderDetail.setOrdetailModifyTime(LocalDateTime.now());
            cOrderDetail.setDataFrom(plantId);
            cOrderDetail.setOrdetailDeleted(0);
            iCOrderDetailService.updateById(cOrderDetail);*/
        }
    }


    /**
     * 修改充值记录
     *
     * @param id//充值记录id
     * @param financeEnterRemark//充值备注
     * @param token
     * @return
     */
    @Transactional
    public SzResult updateRechargeRecord(String id, String financeEnterRemark, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }
        String financeSubjectId = cFinaceEnter.getFinanceSubjectId();
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", financeSubjectId);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper2);
        //审批-修改充值记录
//        QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.eq("IF_ON", 1);
//        queryWrapper3.eq("DEL_FLAG", 0);
//        queryWrapper3.eq("DATA_FROM", plantId);
//        queryWrapper3.eq("APPROVE_NAME", "updateRechargeRecord");
//        TApprove tApprove = approveService.getOne(queryWrapper3);
//        if (tApprove != null) {//开启了审批，创建审批信息
//            TApproveInfo tApproveInfo = new TApproveInfo();
//            tApproveInfo.setApproveId(tApprove.getId());
//            tApproveInfo.setApproveTier(tApprove.getApproveTier());
//            tApproveInfo.setApproveState(0);
//            tApproveInfo.setCreateBy(user.getTrueName());
//            tApproveInfo.setCreateTime(LocalDateTime.now());
//            tApproveInfo.setDelFlag(0);
//            tApproveInfo.setApproveRemark("");
//            tApproveInfo.setApproveInfo(logMsg.toString());
//            tApproveInfo.setDataFrom(plantId);
//            Map<String, Object> map = new HashMap<>();
//            map.put("userId", user.getId());
//            map.put("trueName", user.getTrueName());
//            map.put("plantId", plantId);
//            map.put("ids", id);
//            map.put("financeEnterRemark", financeEnterRemark);
//            String s = JSON.toJSONString(map);
//            tApproveInfo.setExecutionData(s);
//            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的修改充值记录：\n【" + logMsg + " 】");
//            approveInfoService.save(tApproveInfo);
//            return SzResult.error("该功能需审批,请等待审批");
//        }
        if (financeEnterRemark != null && !financeEnterRemark.isEmpty()) {
            cFinaceEnter.setFinanceEnterRemark(financeEnterRemark);//充值备注
        }
        cFinaceEnter.setDownedID1(0);
        iCFinaceEnterService.updateById(cFinaceEnter);
        logMsg.append("修改了款项进账记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(cCompanys.getCpyCo()).append(".").append(cCompanys.getCpyChico()).append("的备注,由").append(cFinaceEnter.getFinanceEnterRemark()).append("改为").append(financeEnterRemark).append("】");

        sysLogBu.logRecord("款项进账", user.getTrueName(), logMsg.toString(), plantId);
        return SzResult.Success();
    }

    //删除充值记录
    @Transactional
    public SzResult deleteRechargeRecord(String id, String plantId, String token) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }

        //审批-删除充值记录
        QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("IF_ON", 1);
        queryWrapper3.eq("DEL_FLAG", 0);
        queryWrapper3.eq("DATA_FROM", plantId);
        queryWrapper3.eq("APPROVE_NAME", "deleteRechargeRecord");
        TApprove tApprove = approveService.getOne(queryWrapper3);

        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo(logMsg.toString());
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getId());
            map.put("trueName", user.getTrueName());
            map.put("plantId", plantId);
            map.put("id", id);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的删除款项进账记录审批：\n【" + logMsg + " 】");
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        Integer financeEntered = cFinaceEnter.getFinanceEntered();
        if (financeEntered == 1) {//已入账
            BigDecimal financeEnterNum = cFinaceEnter.getFinanceEnterNum();
            //余额减去充值金额
            QueryWrapper<COrderDetail> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ORDETAIL_CO", cFinaceEnter.getFinanceEnterCo());
            queryWrapper2.eq("ORDETAIL_CHICO", cFinaceEnter.getFinanceEnterChiCo());
            queryWrapper2.eq("ORDETAIL_SUB_ID", cFinaceEnter.getFinanceSubjectId());
            queryWrapper2.eq("ORDETAIL_DELETED", 0);
            COrderDetail one = iCOrderDetailService.getOne(queryWrapper2);
            if (one == null) {
                return SzResult.error("该公司的余额账户不存在");
            }
            BigDecimal ordetailRemainNum = one.getOrdetailRemainNum();
            BigDecimal subtract = ordetailRemainNum.subtract(financeEnterNum);
//            总计充值金额减去充值金额
            BigDecimal financeEnterTotal = one.getOrdetailItemNum();
            BigDecimal subtract1 = financeEnterTotal.subtract(financeEnterNum);
            one.setOrdetailRemainNum(subtract);
            one.setOrdetailItemNum(subtract1);
            one.setDownedID1(0);
            iCOrderDetailService.updateById(one);
            cFinaceEnter.setFinanceEnterDeleted(1);
        } else if (financeEntered == 0) {
            cFinaceEnter.setFinanceEnterDeleted(1);
            cFinaceEnter.setDownedID1(0);
        }
        iCFinaceEnterService.updateById(cFinaceEnter);

        String financeSubjectId = cFinaceEnter.getFinanceSubjectId();
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", financeSubjectId);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper2);
        logMsg.append("删除了款项进账记录【").append("/n").append("充值编号为:").append(cFinaceEnter.getFinanceEnterId()).append("/n").append("充值公司为:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("/n").append("收款单位为:").append(cCompanys.getCpyCo()).append(".").append(cCompanys.getCpyChico()).append("/n").append("充值金额为:").append(cFinaceEnter.getFinanceEnterNum()).append("的记录】");
        sysLogBu.logRecord("款项进账", user.getTrueName(), logMsg.toString(), plantId);
        return SzResult.Success();
    }


/*    //是否通过一级审批,SFN_FINANCE_APPRVED
    public SzResult sfnFianceApprove(String id, String fianceApproveStatus) throws Exception {
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }
        if (fianceApproveStatus.equals("1")) {//通过
            //判断是否开启一级审批
            QueryWrapper<SysDic> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("DIC_KEY", "financeApprove");
            SysDic sysDic = iSysDicService.getOne(queryWrapper2);
            if (sysDic == null) {
                return SzResult.error("没有这个系统参数");
            }
            String dicVal = sysDic.getDicVal();
            if (dicVal.equals("0")) {
                return SzResult.error("未开启一级审批");
            }
            cFinaceEnter.setSfnFinanceApprved(1);
        } else {//不通过
            cFinaceEnter.setSfnFinanceApprved(0);
        }
        cFinaceEnter.setDownedID1(0);
        iCFinaceEnterService.updateById(cFinaceEnter);
        return SzResult.Success();
    }*/

/*    //是否通过二级审批,SFN_FINANCE_APPRVED2,开启二级审批的前提是要开启一级审批，否则不能开启
    @Transactional
    public SzResult sfnFianceApprove2(String id, String financeApprove2Status) {
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }
        //是否通过了一级审批
        String sfnFianceApprove = String.valueOf(cFinaceEnter.getSfnFinanceApprved());
        if (sfnFianceApprove.equals("0")) {
            return SzResult.error("请先通过一级审批");
        }
        if (financeApprove2Status.equals("1")) {//通过
            QueryWrapper<SysDic> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("DIC_KEY", "financeApprove2");
            SysDic sysDic = iSysDicService.getOne(queryWrapper2);
            if (sysDic == null) {
                return SzResult.error("没有这个系统参数");
            }
            String dicVal = sysDic.getDicVal();
            if (dicVal.equals("0")) {
                return SzResult.error("未开启二级审批");
            }
            cFinaceEnter.setSfnFinanceApprved2(1);
        } else {//不通过
            cFinaceEnter.setSfnFinanceApprved2(0);
        }
        cFinaceEnter.setDownedID1(0);
        iCFinaceEnterService.updateById(cFinaceEnter);
        return SzResult.Success();
    }*/

    @Transactional
    //是否充值成功,FINANCE_ENTERED
    public SzResult sfnFianceEnter(String id, String sfnFianceEnterStatus) throws Exception {
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }
        if (sfnFianceEnterStatus.equals("1")) {//通过
            cFinaceEnter.setFinanceEntered(1);
        } else {//不通过
            cFinaceEnter.setFinanceEntered(0);
        }
        cFinaceEnter.setDownedID1(0);
        iCFinaceEnterService.updateById(cFinaceEnter);
        return SzResult.Success();
    }


    /**
     * 充值记录设置
     *
     * @param id
     * @param sfnFianceEnterStatus 是否充值成功,1是通过,0是不通过
     * @return
     */
    public SzResult rechargeRecordSetting(String id, String sfnFianceEnterStatus, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<CFinaceEnter> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("FINANCE_ENTER_DELETED", 0);
        CFinaceEnter cFinaceEnter = iCFinaceEnterService.getOne(queryWrapper1);
        if (cFinaceEnter == null) {
            return SzResult.error("充值记录不存在");
        }
        Integer financeEntered = cFinaceEnter.getFinanceEntered();
        String flag = null;
        String flag1= null;
        if (financeEntered==1){
            flag="已入账";
        }
        if (financeEntered==0){
            flag="未入账";
        }
        if (Integer.parseInt(sfnFianceEnterStatus)==1){
            flag1="已入账";
        }
        if (Integer.parseInt(sfnFianceEnterStatus)==0){
            flag1="未入账";
        }
        String financeEnterCo = cFinaceEnter.getFinanceEnterCo();
        String financeEnterChiCo = cFinaceEnter.getFinanceEnterChiCo();
        QueryWrapper<CCompanys> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("CPY_CO", financeEnterCo);
        queryWrapper2.eq("CPY_CHICO", financeEnterChiCo);
        queryWrapper2.eq("CPY_DELETED", 0);
        CCompanys cCompanys = iCCompanysService.getOne(queryWrapper2);
        String targetCoId = String.valueOf(cFinaceEnter.getFinanceSubjectId());
        QueryWrapper<CCompanys> targetCoQueryWrapper = new QueryWrapper<>();
        targetCoQueryWrapper.eq("ID", targetCoId);
        CCompanys targetCo = iCCompanysService.getOne(targetCoQueryWrapper);
        if (cCompanys == null) {
            return SzResult.error("充值公司不存在");
        }
        String cpyId = String.valueOf(cCompanys.getId());
        if (financeEntered == 1 && Integer.parseInt(sfnFianceEnterStatus) == 1) {
            return SzResult.Success();
        }
        if (financeEntered == 0 && Integer.parseInt(sfnFianceEnterStatus) == 0) {
            return SzResult.Success();
        }
        QueryWrapper<COrderDetail> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("ORDETAIL_CO", financeEnterCo);
        queryWrapper4.eq("ORDETAIL_CHICO", financeEnterChiCo);
        queryWrapper4.eq("ORDETAIL_SUB_ID", cFinaceEnter.getFinanceSubjectId());
        queryWrapper4.eq("ORDETAIL_DELETED", 0);
        COrderDetail one = iCOrderDetailService.getOne(queryWrapper4);
        if (one == null) {
            return SzResult.error("该公司的余额账户不存在");
        }
        //logMsg.append("修改了充值记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(cCompanys.getCpyCo()).append(".").append(cCompanys.getCpyChico()).append("的充值状态,由").append(cFinaceEnter.getFinanceEntered()).append("改为").append(sfnFianceEnterStatus).append("】");
//        logMsg.append("审批了款项进账记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(targetCo.getCpyCo()).append(".").append(targetCo.getCpyChico()).append("的记录的是否充值成功由").append(flag).append("改为").append(flag1).append("】");

        //审批-充值记录设置
        QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("IF_ON", 1);
        queryWrapper3.eq("DEL_FLAG", 0);
        queryWrapper3.eq("DATA_FROM", plantId);
        queryWrapper3.eq("APPROVE_NAME", "rechargeRecordSetting");
        TApprove tApprove = approveService.getOne(queryWrapper3);

        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo(logMsg.toString());
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getId());
            map.put("trueName", user.getTrueName());
            map.put("sfnFianceEnterStatus", sfnFianceEnterStatus);
            map.put("plantId", plantId);
            map.put("id", id);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的充值记录设置审批：\n【" + logMsg + " 】");
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        //没开审批,直接修改
        if (financeEntered == 0 && Integer.parseInt(sfnFianceEnterStatus) == 1) {//通过

            //打款
            String financeEnterNum = String.valueOf(cFinaceEnter.getFinanceEnterNum());
            String financeEnterCoId = String.valueOf(cpyId);

            this.addOrderDetail(financeEnterNum, financeEnterCoId, targetCoId,plantId);
            cFinaceEnter.setFinanceEntered(1);

            logMsg.append("审批了款项进账记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(targetCo.getCpyCo()).append(".").append(targetCo.getCpyChico()).append("的记录的是否充值成功改为通过").append("】");


        } else if (financeEntered == 1 && Integer.parseInt(sfnFianceEnterStatus) == 0) {//bu通过
            //扣钱
            cFinaceEnter.setSfnFinanceApprved(1);
            BigDecimal financeEnterNumValue = cFinaceEnter.getFinanceEnterNum();
            String financeEnterNum = String.valueOf(financeEnterNumValue.negate());
            String financeEnterCoId = String.valueOf(cpyId);
            this.addOrderDetail(financeEnterNum, financeEnterCoId, targetCoId,plantId);
            cFinaceEnter.setFinanceEntered(0);
            cFinaceEnter.setSfnFinanceApprved(0);
            logMsg.append("审批了款项进账记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(targetCo.getCpyCo()).append(".").append(targetCo.getCpyChico()).append("的记录的是否充值成功为不通过").append("】");
        }else if (financeEntered == 0 && Integer.parseInt(sfnFianceEnterStatus) == 0) {//bu通过
            cFinaceEnter.setFinanceEntered(0);
            cFinaceEnter.setSfnFinanceApprved(0);
            logMsg.append("审批了款项进账记录【").append("充值编号:").append(cFinaceEnter.getFinanceEnterId()).append("充值公司:").append(cFinaceEnter.getFinanceEnterCo()).append(".").append(cFinaceEnter.getFinanceEnterChiCo()).append("收款单位:").append(targetCo.getCpyCo()).append(".").append(targetCo.getCpyChico()).append("的记录的是否充值成功为不通过").append("】");
        }
        cFinaceEnter.setFinanceApprver(user.getTrueName());
        cFinaceEnter.setFinanceApprvTm(LocalDateTime.now());
        iCFinaceEnterService.updateById(cFinaceEnter);
        sysLogBu.logRecord("款项进账", user.getTrueName(), logMsg.toString(), plantId);
        return SzResult.Success();
    }


    @Async
    public Future<List<BalanceEnquiryExcelEn>> balanceEnquiryExportExcel
            (List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean
                    isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String
                     token, String ordetailCo, String startTime, String endTime) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<BalanceEnquiryExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为BalanceEnquiryExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        BalanceEnquiryExcelEn balanceEnquiryExcelEn = BalanceEnquiryExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("ordetailCo")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailCo(entry.getValue().toString());
                                }
                            }
//                            //                            ordetailSubName
                            if (entry.getKey().equals("ordetailSubName")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailSubName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("ordetailLastinNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailLastinNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("ordetailRemainNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailRemainNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksType
                            if (entry.getKey().equals("balanceEnd")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setBalanceEnd(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksInfoApproved
                            if (entry.getKey().equals("balanceConsume")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setBalanceConsume(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksEmiss
                            if (entry.getKey().equals("ordetailItemNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailItemNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                        }
                        list.add(balanceEnquiryExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<COrderDetail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(ordetailCo != null && !ordetailCo.equals(""), "ORDETAIL_CO", ordetailCo);
                    queryWrapper.eq("ORDETAIL_DELETED", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
           /*         queryWrapper.orderByDesc("TRUCKS_QUEUE_STATUS");
                    queryWrapper.orderByDesc("TRUCKS_ID");*/
                    List<COrderDetail> cOrderDetails = iCOrderDetailService.list(queryWrapper);

                    for (COrderDetail cOrderDetail : cOrderDetails) {
                        CCompanys cCompanys = cCompanysMapper.getCompanyById(cOrderDetail.getOrdetailSubId(), plantId);
                        BalanceEnquiryExcelEn balanceEnquiryExcelEn = BalanceEnquiryExcelEn.builder()
                                .ordetailCo(Optional.of(cOrderDetail.getOrdetailCo()+"."+cOrderDetail.getOrdetailChico()).orElse(""))
                                .ordetailSubName(Optional.of(cCompanys.getCpyCo() + "." + cCompanys.getCpyChico()).orElse(""))
                                .ordetailRemainNum(cOrderDetail.getOrdetailRemainNum())
                                .balanceEnd(new BigDecimal((balanceDic.balanceDic(startTime, endTime, cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), cOrderDetail, plantId)).get("balanceEnd")))
                                .balanceConsume(new BigDecimal((balanceDic.balanceDic(startTime, endTime, cOrderDetail.getOrdetailCo(), cOrderDetail.getOrdetailChico(), cOrderDetail, plantId)).get("balanceCons")))
                                .ordetailItemNum(new BigDecimal(String.valueOf(cOrderDetail.getOrdetailItemNum())))
                                .ordetailLastinNum(cOrderDetail.getOrdetailLastinNum())
                                .build();
                        list.add(balanceEnquiryExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为BalanceEnquiryExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        BalanceEnquiryExcelEn balanceEnquiryExcelEn = BalanceEnquiryExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {


                            if (entry.getKey().equals("ordetailCo")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailCo(entry.getValue().toString());
                                }
                            }
                            //                            //                            ordetailSubName
                            if (entry.getKey().equals("ordetailSubName")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailSubName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("ordetailLastinNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailLastinNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("ordetailRemainNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailRemainNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksType
                            if (entry.getKey().equals("balanceEnd")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setBalanceEnd(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksInfoApproved
                            if (entry.getKey().equals("balanceConsume")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setBalanceConsume(new BigDecimal(entry.getValue().toString()));
                                }
                            }
//                                trucksEmiss
                            if (entry.getKey().equals("ordetailItemNum")) {
                                if (entry.getValue() != null) {
                                    balanceEnquiryExcelEn.setOrdetailItemNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                        }
                        list.add(balanceEnquiryExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);


    }


    //    导出余额excel
    @Async
    public Future<List<RechargeRecordExcelEn>> rechargeRecordExportExcel
    (List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean
            isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String token,
     String co, String startTime, String endTime, String plantId) throws Exception {
        // String plantId = plantId;
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<RechargeRecordExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为TruckExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        RechargeRecordExcelEn balanceEnquiryExcelEn = RechargeRecordExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("financeEnterId")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterId("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterId(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("financeEnterCo")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterCo("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterCo(entry.getValue().toString());
                                }
                            }
//                                trucksType
                            if (entry.getKey().equals("financeEnterNum")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterNum(BigDecimal.valueOf(0));
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("financeSubjectName")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceSubjectName("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceSubjectName(entry.getValue().toString());
                                }
                            }
//                                trucksInfoApproved
                            if (entry.getKey().equals("exchangeNo")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setExchangeNo("");
                                } else {
                                    balanceEnquiryExcelEn.setExchangeNo(entry.getValue().toString());
                                }
                            }
//                                trucksPriv
                            if (entry.getKey().equals("financeEnterOperator")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterOperator("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterOperator(entry.getValue().toString());
                                }
                            }
//                                trucksEmiss
                            if (entry.getKey().equals("financeEnterTime")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterTime("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterTime(entry.getValue().toString());
                                }
                            }
//                                trucksAxles
                            if (entry.getKey().equals("financeApprver")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprver("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprver(entry.getValue().toString());
                                }
                            }
//                                trucksLength
                            if (entry.getKey().equals("financeApprvTm")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprvTm("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprvTm(entry.getValue().toString());
                                }
                            }
//                                trucksMaster
                            if (entry.getKey().equals("financeApprverStatus")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved(entry.getValue().toString());
                                }
                            }
//                                trucksIdentity
                            if (entry.getKey().equals("financeApprver2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprver2("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprver2(entry.getValue().toString());
                                }
                            }
//                                trucksTell
                            if (entry.getKey().equals("financeApprvTm2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprvTm2("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprvTm2(entry.getValue().toString());
                                }
                            }
//                                trucksRegMan
                            if (entry.getKey().equals("sfnFinanceApprved")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved(cFinaceEnterDic.getSfnFinanceApprvedDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag1
                            if (entry.getKey().equals("sfnFinanceApprved2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved2("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved2(cFinaceEnterDic.getSfnFinanceApprvedDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag2
                            if (entry.getKey().equals("financeEntered")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEntered("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEntered(cFinaceEnterDic.getFinanceEnteredDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag3
                        }
                        list.add(balanceEnquiryExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<CFinaceEnter> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(co != null && !co.equals(""), "FINANCE_ENTER_CO", co);
                    queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "FINANCE_ENTER_TIME", startTime, endTime);
                    queryWrapper.eq("FINANCE_ENTER_DELETED", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
                    queryWrapper.orderByDesc("FINANCE_ENTER_TIME");
                    List<CFinaceEnter> cFinaceEnters = iCFinaceEnterService.list(queryWrapper);
                    for (CFinaceEnter cFinaceEnter : cFinaceEnters) {
                        CCompanys companys = iCCompanysService.getById(cFinaceEnter.getFinanceSubjectId());
                        RechargeRecordExcelEn balanceEnquiryExcelEn = RechargeRecordExcelEn.builder()
                                .financeSubjectName(Optional.of(companys.getCpyCo()+"."+companys.getCpyChico()).map(Object::toString).orElse(""))
//                                  financeEnterId
                                .financeEnterId(Optional.ofNullable(cFinaceEnter.getFinanceEnterId()).map(Object::toString).orElse(""))
//                            financeEnterCo
                                .financeEnterCo(Optional.of(cFinaceEnter.getFinanceEnterCo()+"."+cFinaceEnter.getFinanceEnterChiCo()).map(Object::toString).orElse(""))
//                            financeEnterNum
                                .financeEnterNum(cFinaceEnter.getFinanceEnterNum())
//                            financeApprver2
                                .financeApprver2(Optional.ofNullable(cFinaceEnter.getFinanceApprver2()).map(Object::toString).orElse(""))
//                            financeApprvTm2
                                .financeApprvTm2(Optional.of(cFinaceEnter.getFinanceApprvTm2().toString().replace("T"," ")).map(Object::toString).orElse(""))
//                            sfnFinanceApprved2
                                .sfnFinanceApprved2(Optional.ofNullable(cFinaceEnterDic.getSfnFinanceApprved2Dic(cFinaceEnter.getSfnFinanceApprved2())).map(Object::toString).orElse(""))
//                            cFinaceEnterDic
                                .sfnFinanceApprved(Optional.ofNullable(cFinaceEnterDic.getSfnFinanceApprvedDic(cFinaceEnter.getSfnFinanceApprved())).map(Object::toString).orElse(""))
//                            financeEntered
                                .financeEntered(Optional.ofNullable(cFinaceEnterDic.getFinanceEnteredDic(cFinaceEnter.getFinanceEntered())).map(Object::toString).orElse(""))
//                            exchangeNo
                                .exchangeNo(Optional.ofNullable(cFinaceEnter.getExchangeNo()).map(Object::toString).orElse(""))
//                            financeEnterTime
                                .financeEnterTime(Optional.of(cFinaceEnter.getFinanceEnterTime().toString().replace("T"," ")).map(Object::toString).orElse(""))
//                            financeApprver
                                .financeApprver(Optional.ofNullable(cFinaceEnter.getFinanceApprver()).map(Object::toString).orElse(""))
//                            financeApprvTm
                                .financeApprvTm(Optional.of(cFinaceEnter.getFinanceApprvTm().toString().replace("T"," ")).map(Object::toString).orElse(""))
                                .build();
                        list.add(balanceEnquiryExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为TruckExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        RechargeRecordExcelEn balanceEnquiryExcelEn = RechargeRecordExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("financeEnterId")) {
                                if (entry.getValue() == null || entry.getValue().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterId("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterId(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("financeEnterCo")) {
                                if (entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterCo("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterCo(entry.getValue().toString());
                                }
                            }

//                            ordetailSubName
                            if (entry.getKey().equals("financeEnterTime")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterTime("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterTime(entry.getValue().toString());
                                }
                            }
//                                trucksType
                            if (entry.getKey().equals("financeEnterNum")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterNum(BigDecimal.valueOf(0));
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterNum(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("financeSubjectName")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceSubjectName("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceSubjectName(entry.getValue().toString());
                                }
                            }
//                                trucksInfoApproved
                            if (entry.getKey().equals("exchangeNo")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setExchangeNo("");
                                } else {
                                    balanceEnquiryExcelEn.setExchangeNo(entry.getValue().toString());
                                }
                            }
//                                trucksPriv
                            if (entry.getKey().equals("financeEnterOperator")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterOperator("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterOperator(entry.getValue().toString());
                                }
                            }
//                                trucksEmiss
                            if (entry.getKey().equals("financeEnterTime")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEnterTime("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEnterTime(entry.getValue().toString());
                                }
                            }
//                                trucksAxles
                            if (entry.getKey().equals("financeApprver")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprver("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprver(entry.getValue().toString());
                                }
                            }
//                                trucksLength
                            if (entry.getKey().equals("financeApprvTm")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprvTm("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprvTm(entry.getValue().toString());
                                }
                            }
//                                trucksMaster
                            if (entry.getKey().equals("financeApprverStatus")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved(entry.getValue().toString());
                                }
                            }
//                                trucksIdentity
                            if (entry.getKey().equals("financeApprver2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprver2("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprver2(entry.getValue().toString());
                                }
                            }
//                                trucksTell
                            if (entry.getKey().equals("financeApprvTm2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceApprvTm2("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceApprvTm2(entry.getValue().toString());
                                }
                            }
//                                trucksRegMan
                            if (entry.getKey().equals("sfnFinanceApprved")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved(cFinaceEnterDic.getSfnFinanceApprvedDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag1
                            if (entry.getKey().equals("sfnFinanceApprved2")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved2("");
                                } else {
                                    balanceEnquiryExcelEn.setSfnFinanceApprved2(cFinaceEnterDic.getSfnFinanceApprvedDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag2
                            if (entry.getKey().equals("financeEntered")) {
                                if (entry.getValue() == null || entry.getValue().toString().equals("")) {
                                    balanceEnquiryExcelEn.setFinanceEntered("");
                                } else {
                                    balanceEnquiryExcelEn.setFinanceEntered(cFinaceEnterDic.getFinanceEnteredDic(Integer.parseInt(entry.getValue().toString())));
                                }
                            }
//                                trucksTag3
                        }
                        list.add(balanceEnquiryExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }

    /**
     * 查询授信
     *
     * @param ordetailId 单位的id
     */
    public SzResult credit(String ordetailId, String token, String plantId) {
        String cpyCo = "";
        String cpyChico = "";
        if (ordetailId != null && !ordetailId.equals("")) {
            QueryWrapper<CCompanys> companysQueryWrapper = new QueryWrapper<>();
            companysQueryWrapper.eq(true, "ID", ordetailId);
            companysQueryWrapper.eq("CPY_DELETED", 0);
            companysQueryWrapper.eq("DATA_FROM", plantId);
            CCompanys cCompanys = iCCompanysService.getOne(companysQueryWrapper);
            cpyCo = cCompanys.getCpyCo();
            cpyChico = cCompanys.getCpyChico();
        }
        QueryWrapper<COrderDetail> ordetailQueryWrapper = new QueryWrapper<>();
        ordetailQueryWrapper.eq(cpyCo != null && !cpyCo.equals(""), "ORDETAIL_CO", cpyCo);
        ordetailQueryWrapper.eq(cpyChico != null && !cpyChico.equals(""), "ORDETAIL_CHICO", cpyChico);
        ordetailQueryWrapper.eq("ORDETAIL_DELETED", 0);
        ordetailQueryWrapper.eq("DATA_FROM", plantId);
        List<COrderDetail> list = iCOrderDetailService.list(ordetailQueryWrapper);
        List<CreditVo> creditVoList = new ArrayList<>();
        for (COrderDetail cOrderDetail : list) {
            CreditVo creditVo = new CreditVo();
            creditVo.setId(String.valueOf(cOrderDetail.getId()));
            creditVo.setOrdetailCo(cOrderDetail.getOrdetailCo());
            creditVo.setOrdetailChiCo(cOrderDetail.getOrdetailChico());
            creditVo.setCredit(String.valueOf(cOrderDetail.getOrdetailPreLic()));
            creditVo.setOrdetailRemainNum(String.valueOf(cOrderDetail.getOrdetailRemainNum()));
            creditVo.setOrdetailSubId(String.valueOf(cOrderDetail.getOrdetailSubId()));
            creditVoList.add(creditVo);
        }
        return SzResult.success(creditVoList);
    }

    /**
     * 修改信用
     *
     * @param id
     * @param credit
     * @param token
     * @return
     */
    public SzResult updateCredit(String id, String credit, String token, String plantId) throws Exception {
        //String plantId = plantId;
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<COrderDetail> ordetailQueryWrapper = new QueryWrapper<>();
        ordetailQueryWrapper.eq("ID", id);
        COrderDetail one = iCOrderDetailService.getOne(ordetailQueryWrapper);
        BigDecimal ordetailPreLic = one.getOrdetailPreLic();
        one.setOrdetailPreLic(BigDecimal.valueOf(Integer.parseInt(credit)));
        one.setDownedID1(0);
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IF_ON", 1);
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq("APPROVE_NAME", "credit");
        TApprove tApprove = approveService.getOne(queryWrapper);
        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveBelongId(String.valueOf(one.getOrdetailId()));
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的修改授信额度审批：【" + "将" + one.getOrdetailCo() + "." + one.getOrdetailChico() + "单位的授信额度由" + ordetailPreLic + "修改为" + credit + "】");
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("credit", credit);
            map.put("co", one.getOrdetailCo());
            map.put("chiCo", one.getOrdetailChico());
            map.put("subCoId", one.getOrdetailSubId());
            map.put("plantId", plantId);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        iCOrderDetailService.updateById(one);
        sysLogBu.logRecord("修改授信额度", user.getTrueName(), "将" + one.getOrdetailCo() + "." + one.getOrdetailChico() + "单位的授信额度由" + ordetailPreLic + "修改为" + credit + "】", plantId);
        return SzResult.Success();
    }
}
